#!/usr/bin/env python

# This File Contain Object that is related to concept of webpage

from BeautifulSoup import BeautifulSoup
from ItemParser import * 
from URL import URL


class Webpage(object):
	'''Class to abstract Webpage'''
	pageNum = 0;

	def __init__(self, path):
		print 'Initializing Webpage...'
		Webpage.pageNum += 1
		self.urlManager = URL()

		self.html = self.urlManager.LoadURL(path)
		self.soup = BeautifulSoup(self.html)

	def __del__(self):
		print "Deleting Webpage..."
		Webpage.pageNum -= 1

class HistCiteWebpage2010(Webpage):
	def __init__(self, path, MODULE_NAME = '', ItemParser='', InitLater = ''):
		print 'Initialize HistCiteWebpage2010...'
		Webpage.__init__(self, path);

		if ItemParser == '':
			self.OldItemParser = ItemParser2010(MODULE_NAME)
		else:
			self.OldItemParser = ItemParser

		self.MODULE_NAME = MODULE_NAME

		if InitLater == '':
			self.InitHTML()
	
	def __del__(self):
		print 'Deleting OldHistCiteWebpage...'
		Webpage.__del__(self)

	def InitHTML(self):
		self.tr = []
		self.AddAllLine()
	
		# indexPageURL = self.CheckPageNum()
		# print 'indexPagaURL: '
		# print indexPageURL
		pageNum = self.CheckPageNum()
		# print pageNum

		# for addr in indexPageURL:
		for i in range(pageNum):
			print 'Load Index Page [' + str(i+1) + ']'
			addr = 'index-tl-' + str(i+1) + '.html'
			root = './data/' + self.MODULE_NAME + '/'
			self.html = self.urlManager.LoadURL(root + addr)
			self.soup = BeautifulSoup(self.html)
			self.AddAllLine()

		self.ItemNum = len(self.tr)
		# print self.ItemNum
		# import pdb
		# pdb.set_trace()


	# overLoad Function 
	def CheckPageNum(self):
		print 'Enter CheckPageNum'
		res = self.soup.body.findAll("a", href=re.compile('index-tl-\d+\.html'))

		pageNum = int( res[-1].renderContents() )
		return pageNum
		
		# import pdb
		# pdb.set_trace()
		
		# DON'T DELETE
		# indexPageURL = [{}] * ( len(res) / 2  )
		# for m in range(len(res)/2):
		#         a2 = res[m]
		#         indexPageURL[m] = a2['href']
		# return indexPageURL 
        
        # Overloaded Function
	# Get All Line of Current Page. Each page have multiple tables and
	# each table contains a lot of lines. This function split each line in
	# each table and comcate them into self.tr array. 
	def AddAllLine(self):
		print 'Entering AddAllLine()...'
		table = self.soup.findAll("table", {"border":"0", "width":"100%"})	
		# self.tr = []
		for t in table:
			# Get all lines For Each Table and Concate them
			self.tr += t.findAll("tr", {"valign":"top"}) 


	# Get Attribute for Each Item. 
	def GetItem(self, n):
                print 'Entering GetItem()'
		if n <=0 or n > len(self.tr):
			print 'Error in GetItem: index out of range'
			return
		data = self.OldItemParser.Parse(self.tr[n-1])
		return data




